package cn.iocoder.yudao.module.book.service.community;

import cn.iocoder.yudao.module.book.controller.app.community.vo.TopicRespVO;
import cn.iocoder.yudao.module.book.dal.dataobject.community.TopicsDO;
import cn.iocoder.yudao.module.book.dal.mysql.community.TopicsMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 话题 Service 实现类
 *
 * @author system
 */
@Service
public class TopicsServiceImpl implements TopicsService {

    @Resource
    private TopicsMapper topicsMapper;

    @Override
    public List<TopicRespVO> getHotTopics(Integer limit) {
        List<TopicsDO> topics = topicsMapper.selectHotTopics(limit != null ? limit : 10);
        return topics.stream()
                .map(this::convertToRespVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<TopicRespVO> searchTopics(String keyword) {
        List<TopicsDO> topics = topicsMapper.searchTopics(keyword);
        return topics.stream()
                .map(this::convertToRespVO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrGetTopic(String topicName) {
        // 1. 查询是否已存在
        TopicsDO existingTopic = topicsMapper.selectByTopicName(topicName);
        if (existingTopic != null) {
            return existingTopic.getTopicId();
        }

        // 2. 创建新话题
        TopicsDO topic = TopicsDO.builder()
                .topicName(topicName)
                .topicDescription("")
                .postsCount(0)
                .followersCount(0)
                .isHot(0)
                .status(1)
                .build();
        topicsMapper.insert(topic);

        return topic.getTopicId();
    }

    /**
     * 转换为响应VO
     */
    private TopicRespVO convertToRespVO(TopicsDO topic) {
        TopicRespVO respVO = new TopicRespVO();
        respVO.setTopicId(topic.getTopicId());
        respVO.setTopicName(topic.getTopicName());
        respVO.setTopicDescription(topic.getTopicDescription());
        respVO.setPostsCount(topic.getPostsCount());
        respVO.setFollowersCount(topic.getFollowersCount());
        respVO.setIsHot(topic.getIsHot() == 1);
        return respVO;
    }

}
